﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using RibbonEditor.CommandUIDefinitionClasses;
using RibbonEditor._Global;
using RibbonEditor.AppCode;

namespace RibbonEditor
{
    public class CustomAction : ICustomAction, IXmlBuildable
    {
        public string Id { get; set; }
        public string Location { get; set; }
        public int? Sequence { get; set; }
        public CommandUIDefinition cmdUIDef { get; set; }

        public CustomAction()
        {
            this.cmdUIDef = new CommandUIDefinition(); 
        }

        public CustomAction(XmlNode node)
        {
            try
            {
                this.Id = XmlHelper.GetAttribute(node, "Id");
                this.Location = XmlHelper.GetAttribute(node, "Location");
                this.Sequence = XmlHelper.GetNullableIntAttribute(node, "Sequence");
                this.cmdUIDef = new CommandUIDefinition(node.SelectSingleNode("CommandUIDefinition"));
            }
            catch (Exception error)
            {
                MessageBox.Show("An error occured: " + error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void AddNode(XmlNode customActionsNode)
        {
            try
            {
                XmlNode customActionNode = XmlHelper.AddNode(customActionsNode, "CustomAction");
                XmlHelper.AddAttribute(customActionNode, "Id", this.Id);
                XmlHelper.AddAttribute(customActionNode, "Location", this.Location);
                XmlHelper.AddAttribute(customActionNode, "Sequence", this.Sequence);

                this.cmdUIDef.AddCommandUIDefinitionNode(customActionNode);
            }
            catch (Exception error)
            {
                MessageBox.Show("An error occured: " + error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void BuildTreeViewElement(TreeNode parentNode)
        {
            try
            {
                TreeNode node = new TreeNode("CustomAction");
                node.ContextMenuStrip = ContextMenuStripHelper.BuildStandardContextMenuStrip(node);
                node.Tag = this;

                this.cmdUIDef.BuildTreeViewElement(node);

                node.Expand();

                parentNode.Nodes.Add(node);
            }
            catch (Exception error)
            {
                MessageBox.Show("An error occured: " + error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
